package com.qiall.bashutil;


import com.alibaba.fastjson.JSON;
import com.qiall.bashutil.event.CommandMessageEvent;
import com.qiall.bashutil.event.MvnPackageSuccessEvent;
import org.apache.maven.shared.invoker.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.xml.bind.util.JAXBSource;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;



public class MavenScripUtil {

    private OsScriptUtil osScriptUtil;



    public static void mvnCommand(String codePath, String command) throws MavenInvocationException {
        InvocationRequest request = new DefaultInvocationRequest();
        String relativelyPath = codePath;
        String pomPath = relativelyPath + "/pom.xml";

        request.setPomFile(new File(pomPath));
        request.setGoals(Collections.singletonList(command));
        Invoker invoker = new DefaultInvoker();
        invoker.setMavenHome(new File("/root/maven/apache-maven-3.3.9"));

        invoker.execute(request);

    }

    public void mvmPackage(String codePath, int appId) {
        String command = "mvn package -DskipTests";

        List<String> commandRet = OsScriptUtil.executeNewFlow(Arrays.asList("cd " + codePath, command));
        CommandMessageEvent commandMessageEvent = new CommandMessageEvent(this, JSON.toJSONString(commandRet), appId);
    //    applicationContext.publishEvent(commandMessageEvent);
        MvnPackageSuccessEvent mvnPackageSuccessEvent = new MvnPackageSuccessEvent(this, appId);
    //    applicationContext.publishEvent(mvnPackageSuccessEvent);
    }


    public void mvnInstall(String codePath, int appId) {
        String command = "mvn install";

        List<String> commandRet = OsScriptUtil.executeNewFlow(Arrays.asList("cd " + codePath, command));
        CommandMessageEvent commandMessageEvent = new CommandMessageEvent(this, JSON.toJSONString(commandRet), appId);
        //    applicationContext.publishEvent(commandMessageEvent);
        MvnPackageSuccessEvent mvnPackageSuccessEvent = new MvnPackageSuccessEvent(this, appId);
        //    applicationContext.publishEvent(mvnPackageSuccessEvent);
    }
}
